package model;

import java.text.NumberFormat;


/**
 * This class is to hold the data value and type of a cell in the table.
 * The data value is kept as an Object and the data type is indicated by
 * a string such that the user can parse the value according to the data
 * type.
 * 
 * @author David, Rex
 */
public class Data {
    private final String mySringValue = "String";

    @SuppressWarnings("rawtypes")
    private Comparable myValue;
    private String myType;

    /**
     * Construct Data Class
     * @param value value
     * @param type type of this value
     */
    @SuppressWarnings("rawtypes")
    public Data (Comparable value, String type) {
        myValue = value;
        myType = type;
    }

    /**
     * Construct data using existing data
     * @param d1 the data to be copied
     */
    public Data (Data d1) {
        myValue = d1.getValue();
        myType = d1.getType();
    }

    /**
     * compare two Data depending on their types
     *
     * @param d another Data to be compared
     * @return integer; positive if this is bigger; negative if this is smaller
     */
    public int compareTo (Data d) {
        if (myType.equals(mySringValue)) {
            return getValue().compareTo(d.getValue());
        }
        else {
            if (Double.parseDouble(getValue()) > Double.parseDouble(d.getValue())) {
                return 1;
            }
            else if (Double.parseDouble(getValue()) == Double.parseDouble(d.getValue())) {
                return 0;
            }
            else {
                return -1;
            }
        }
    }

    /**
     * return the value in String form
     * @return value in String form
     */
    public String getValue () {
        return myValue.toString();
    }

    /**
     * get type of the value
     * @return String or Double
     */
    public String getType () {
        return myType;
    }

    /**
     * @param decimalPlace decimalPlace specified by the user
     * @returna String with specified decimal place
     */
    public String keepDecimalPlace (int decimalPlace) {
        if (myType.equals(mySringValue)) {
            throw new ClassCastException();
        }
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(decimalPlace);
        return nf.format(Double.parseDouble(getValue()));
    }

    /**
     * convert to percentage
     * @return the value in percentage format
     */
    public String convertToPercentage () {
        NumberFormat nf = NumberFormat.getPercentInstance();
        return nf.format(Double.parseDouble(getValue()));
    }
}
